<?php
/**
 * 后台管理系统-登录
 */
namespace app\bews\controller;
use think\App;
use app\AppApi;
use think\facade\Db;
use think\facade\View;
use think\facade\Cookie;
use app\bews\model\BewAdminConfig;

class Login{
	public function index(){
		# 获取配置
		$BewAdminConfig = new BewAdminConfig();
		$this->config = $BewAdminConfig->getAll();
		View::assign([
			'config' => $this->config
		]);
		return View::fetch();
	}
	public function login(){
		$req = request();
		if($req->isPost()){
			$account = trim(input('post.account'));
			if(empty($account)){
				$this->returnCode('90000001');
			}
			$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
			if(!preg_match($pattern,$account)){
				$this->returnCode('90000006');
			}
			$password = trim(input('post.password'));
			if(empty($password)){
				$this->returnCode(1,'密码不能为空');
			}
			$code = trim(input('post.code'));
			if($code == ''){
				$this->returnCode(1,'验证码不能为空');
			}
			if(!captcha_check($code)){
				$this->returnCode(1,'验证码错误');
			}
			$aUser = Db::table('bew_admin_user')->where('account',$account)->find();
			if (empty($aUser)) {
				$this->returnCode('90000029');
			}
			if ($aUser['status'] != 1) {
				$this->returnCode('90000030');
			}
			if($aUser['password'] != md5($password)){
				$this->returnCode('90000031');
			}
			$remember = input('post.remember');
			if(!empty($remember)){
				Cookie::set('admin_id',$aUser['uid'],60*60*24*7);
				Cookie::set('admin_name',$aUser['name'],60*60*24*7);
			}else{
				Cookie::set('admin_id',$aUser['uid']);
				Cookie::set('admin_name',$aUser['name']);
			}
			Db::table('bew_admin_user')->where('uid',$aUser['uid'])->update(
				['times_login' => $aUser['times_login']+1,'time_last' => time()]
			);
			$this->returnCode(0,[],'登陆成功');
		}
	}
	public function logout(){
		Cookie::delete('admin_id');
		Cookie::delete('admin_name');
		$this->returnCode(0,[],'退出成功');
	}
	protected function returnCode($code,$data=[],$msg=''){
		header('Content-type:application/json');
		if($code == 0){
			$arr = array(
				'code'=>$code,
				'msg'=>$msg,
				'data' => $data
			);
		}else if($code == 1){
			$arr = array(
				'code'	=>	1,
				'msg'	=>	$data
			);
		}else{
			$appapi = new AppApi();
			$arr = array(
				'code'=>$code,
				'msg'=>$appapi::errorTip($code)
			);
		}
		echo json_encode($arr);
		if($code != 0){
			exit;
		}
	}
}